<?php
/**
 * Created by PhpStorm.
 * User: Shen
 * Date: 2016/6/22
 * Time: 21:45
 */
//使用递归实现无限级分类
header("Content-type:text/html;charset=utf-8");

include_once 'database.php';

function getList($pid = 0,&$result=array(),$spac=0){
    $spac = $spac + 2;
    $sql = "SELECT * FROM cate WHERE pid = $pid";
    $res = mysql_query($sql);
    while ($row = mysql_fetch_assoc($res)){
        $row['catename'] = str_repeat('&nbsp;&nbsp;',$spac) . '|--' . $row['catename'];
        $result[] = $row;
        getList($row['id'],$result,$spac);
    }
    return $result;
}





function display($pid = 0,$selected=1){
    $rs = getList($pid);
    $str = '';
//print_r($rs);
    $str .= "<select name='cate'>";
    foreach ($rs as $key => $val) {
        $selectedStr = '';
        if ($val['id'] == $selected){
            $selectedStr = "selected";
        }
        $str .= "<option {$selectedStr}>{$val['catename']}</option>";
    }
    $str .= "</select>";

    return $str;
}

echo display(0,3);